package org.ewaf.framework.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.ewaf.framework.task.aware.EngineAware;
import org.ewaf.framework.task.dao.Message;
import org.ewaf.framework.task.dao.MessageDao;
import org.ewaf.framework.task.dao.TaskDao;
import org.springframework.beans.factory.InitializingBean;

public class DefaultEngineAdaptor implements Engine , InitializingBean {

	private TaskDao taskDao;
	private MessageDao messageDao;

	public MessageDao getMessageDao() {
		return messageDao;
	}

	public void setMessageDao(MessageDao messageDao) {
		this.messageDao = messageDao;
	}

	public TaskDao getTaskDao() {
		return taskDao;
	}

	public void setTaskDao(TaskDao taskDao) {
		this.taskDao = taskDao;
	}

	private Map<String, List<Handler>> status2handlers;

	public Map<String, List<Handler>> getStatus2handlers() {
		return status2handlers;
	}

	public void setStatus2handlers(Map<String, List<Handler>> status2handlers) {
		this.status2handlers = status2handlers;
	}

	private String type;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public List<Handler> getHandlers(String id) {

		Message message = messageDao.getMessage(id);
		if (message == null) {
			return new ArrayList<Handler>();
		}

		return getHandlers(message, message.getStatus());
	}

	private List<Handler> getHandlers(Message message, String status) {
		return status2handlers.get(status);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		
		for (List<Handler> handlers : status2handlers.values()) {
			
			for (Handler handler : handlers) {
				
				if(handler  instanceof  EngineAware) {
					((EngineAware)handler).setEngine(this);
				}
				
				/**
				 * TODO : inject env aware
				 */
			}
			
		}
		
	}

}
